package com.example.everying.config;

import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.HttpProtocol;
import reactor.netty.http.client.HttpClient;
import reactor.netty.resources.ConnectionProvider;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Configuration
public class WebClientConfig {

    @Bean
    public WebClient deepSeekWebClient(
            @Value("${spring.ai.openai.base-url}") String baseUrl,
            @Value("${spring.ai.openai.api-key}") String apiKey) {

        // 1. 配置连接池
        ConnectionProvider provider = ConnectionProvider.builder("deepseek-pool")
                .maxConnections(500)
                .pendingAcquireTimeout(Duration.ZERO)
                .build();

        // 2. 配置HTTP客户端（包含HTTP/2）
        HttpClient httpClient = HttpClient.create(provider)
                .protocol(HttpProtocol.HTTP11, HttpProtocol.H2)
                .responseTimeout(Duration.ofSeconds(5))  // 放宽到5秒（DeepSeek可能需要更长时间处理）
                .keepAlive(true) // 必须启用长连接
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000) // 连接超时2秒
                .doOnConnected(conn ->
                        conn.addHandlerLast(new ReadTimeoutHandler(5, TimeUnit.SECONDS)) // 与responseTimeout一致
                );

        // 3. 构建WebClient
        return WebClient.builder()
                .baseUrl(baseUrl)
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
                .build();
    }
}
